import { Menu, BrowserWindow, app, type MenuItem, type MenuItemConstructorOptions } from "electron";

class MenuManager {
  private menuTemplate: (MenuItemConstructorOptions | MenuItem)[] | null = null;
  private win: BrowserWindow | null = null;
  private isDev: boolean;

  constructor(win: BrowserWindow | null, isDev: boolean) {
    this.win = win;
    this.isDev = isDev;
  }

  // 设置主窗口引用
  setMainWindow(win: BrowserWindow) {
    this.win = win;
  }

  // 应用菜单配置
  private appMenu(fullscreenLabel: string) {
    const menuItems = [
      { label: "关于", role: "about" },
      { label: "开发者工具", role: "toggleDevTools" },
      { label: "强制刷新", role: "forcereload" },
      { label: "退出", role: "quit" }
    ];

    if (!this.isDev) menuItems.splice(1, 1);

    return [
      {
        label: app.name,
        submenu: menuItems
      },
      {
        label: "编辑",
        submenu: [
          { label: "撤销", role: "undo" },
          { label: "重做", role: "redo" },
          { type: "separator" },
          { label: "剪切", role: "cut" },
          { label: "复制", role: "copy" },
          { label: "粘贴", role: "paste" },
          { label: "删除", role: "delete" },
          { label: "全选", role: "selectAll" }
        ]
      },
      {
        label: "显示",
        submenu: [
          {
            label: "显示主窗口",
            click: () => {
              if (this.win) {
                this.win.show();
                this.win.focus();
              }
            }
          },
          { type: "separator" },
          { label: "加大", role: "zoomin" },
          { label: "默认大小", role: "resetzoom" },
          { label: "缩小", role: "zoomout" },
          { type: "separator" },
          {
            label: fullscreenLabel,
            role: "togglefullscreen"
          }
        ]
      }
    ];
  }

  // 创建菜单
  createMenu(label = "进入全屏幕") {
    if (!this.menuTemplate) {
      this.menuTemplate = this.appMenu(label) as (MenuItemConstructorOptions | MenuItem)[];
    } else {
      const showMenu = this.menuTemplate.find(item => item.label === "显示") as any;
      if (showMenu) {
        const fullscreenItem = showMenu.submenu?.find(
          item => "role" in item && item.role === "togglefullscreen"
        );
        if (fullscreenItem) {
          fullscreenItem.label = label;
        }
      }
    }

    const menu = Menu.buildFromTemplate(this.menuTemplate);
    Menu.setApplicationMenu(menu);
  }
}

export default MenuManager;